package com.longxi.tianjintianbao.ui.presenter.repair_publish;

import android.content.Intent;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.ui.activity.repair_publish.SelectAreaActivity;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.repair_publish.IRepairContentAtView;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RepairContentAtPresenter extends BasePresenter<IRepairContentAtView> {

    String region = "";// 维修区域
    String repairtype = "";// 维修类型
    String repaircategory ="";// 维修类别
    String buildId = "";//区域id
    public String CUSTTYPE_YG = "1";// 1-员工
    public String CUSTTYPE_ZH = "0";// 0-租户
    public String custtype = CUSTTYPE_YG;

    public RepairContentAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        region =intent.getStringExtra(AppConst.REGION);
        repairtype =intent.getStringExtra(AppConst.REPAIRTYPE);
        repaircategory =intent.getStringExtra(AppConst.REPAIRCATEGORY);
        if(CUSTTYPE_ZH.equals(region)){
            getView().getEtAddress().setEnabled(false);
            getView().getEtAddress().setEnabled(false);
            getView().getEtAddress().setFocusableInTouchMode(false);
        }
        mContext.setTitle(repaircategory);
        mContext.setTvLeft(MyUtils.getString(R.string.back));
    }

    /**
     * 选择小区地址
     */
    public void selectArea() {
        Intent mainIntent = new Intent(mContext, SelectAreaActivity.class);
        Intent intent = mContext.getIntent();
        mainIntent.putExtra(AppConst.REPAIRAREA,intent.getStringExtra(AppConst.REGION));
        mContext.startActivityForResult(mainIntent, AppConst.IntentRequstCode.ACTIVITY_REPAIR_CONTENT);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case AppConst.IntentRequstCode.ACTIVITY_REPAIR_CONTENT:
                if(data != null){
                    buildId = data.getStringExtra("buildId");
                    getView().getTvSelectArea().setText(data.getStringExtra("area"));
                    getView().getEtAddress().setText(data.getStringExtra("address"));
                    if(CUSTTYPE_YG.equals(region)){
                        setYGNamePhone();
                    }else{
                        custtype = CUSTTYPE_ZH;
                        getView().getRgCustomType().check(R.id.rBtnZH);
                        contacts = data.getStringExtra("custname");
                        contactsid = data.getStringExtra("contactsid");
                        contactsphone = data.getStringExtra("contactsphone");
                        setYHNamePhone();
                    }
                }
                break;
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                addPicUtils.selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                for (LocalMedia media : addPicUtils.selectList) {
                    LogUtils.i("图片-----》", media.getPath());
                }
                gridImageAdapter.setList(addPicUtils.selectList);
                gridImageAdapter.notifyDataSetChanged();
                break;
        }
    }

    /**
     * 保存报修
     */
    public void saveEventRepair() {
        long userid = MyApplication.loginUser.userid;
        String addressid = buildId;
        String address = getView().getEtAddress().getText().toString().trim();
        String contacts2 = getView().getEtName().getText().toString().trim();
        String contactsphone2 = getView().getEtPhone().getText().toString().trim();
        String content = getView().getEtContent().getText().toString().trim();
        String image1 = "";
        String image2 = "";
        for (int i = 0; i < addPicUtils.selectList.size(); i++) {
            if(i == 0){
                image1 = MyUtils.imageToBase64(addPicUtils.selectList.get(i).getCompressPath());
            }else if(i == 1){
                image2 = MyUtils.imageToBase64(addPicUtils.selectList.get(i).getCompressPath());
            }
        }

        if("".equals(region) || region == null){
            MyUtils.showToast("维修区域异常");
            return;
        }

        if("".equals(addressid) || addressid == null){
            MyUtils.showToast("请选择小区");
            return;
        }

        if("".equals(address) || address == null){
            MyUtils.showToast("请输入地址");
            return;
        }

        if("".equals(contacts2) || contacts2 == null){
            MyUtils.showToast("请输入报修人名称");
            return;
        }

        if("".equals(contactsphone2) || contactsphone2 == null){
            MyUtils.showToast("请输入报修人电话");
            return;
        }

        if("".equals(content) || content == null){
            MyUtils.showToast("请输入维修内容");
            return;
        }

        if("".equals(dateTime)){
            MyUtils.showToast("请选择预约完成时间");
            return;
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", "");
            object.put("userid", userid);
            object.put("region", region);
            object.put("repairtype", repairtype);
            object.put("repaircategory", repaircategory);
            object.put("addressid", addressid);
            object.put("address", address);
            object.put("contacts", contacts2);
            if(custtype == CUSTTYPE_YG){
                object.put("contactsid", MyApplication.loginUser.userid + "");
            }else{
                object.put("contactsid", contactsid);
            }
            object.put("contactsphone", contactsphone2);
            object.put("content", content);
            object.put("image1", image1);
            object.put("image2", image2);
            object.put("imagereplace", "");
            object.put("arrangedate", dateTime);
            object.put("assetscode", "");
            object.put("assetsname", "");
            object.put("custtype", custtype);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().saveEventRepair(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                MyUtils.showToast("提交成功");
                mContext.finish();
            }
        });
    }

    String contacts = "";
    String contactsid = "";
    String contactsphone = "";

    /**
     * 设置员工信息
     */
    public void setYGNamePhone() {
        custtype = CUSTTYPE_YG;
        getView().getEtName().setText(MyApplication.loginUser.username);
        getView().getEtPhone().setText(MyApplication.loginUser.phone);
    }

    /**
     * 设置用户信息
     */
    public void setYHNamePhone() {
        custtype = CUSTTYPE_ZH;
        getView().getEtName().setText(contacts);
        getView().getEtPhone().setText(contactsphone);
    }
}
